import { Injectable } from '@angular/core';

@Injectable()
export class SessionStorageService {
    private sessionStorage: Storage;

    constructor() {
        if (!sessionStorage) {
            throw new Error('Current browser does not support Session Storage');
        }
        this.sessionStorage = sessionStorage;
    }

    // 存储对象数据
    setObject(key: string, data: any) {
        this.sessionStorage.setItem(key, JSON.stringify(data));
    }

    // 获取对象数据
    getObject(key: string): any {
        const data = this.sessionStorage.getItem(key);
        if (!data) {
            return undefined;
        }
        return JSON.parse(data);
    }

    // 存储值数据
    setValue(key: string, val: string) {
        this.sessionStorage.setItem(key, val);
    }

    // 获取值数据
    getValue(key: string): string {
        return this.sessionStorage.getItem(key);
    }

    // 移除数据
    remove(key: string) {
        this.sessionStorage.removeItem(key);
    }
}
